package com.ruoyi.web.controller.drinkwater;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.drinkwater.domain.ManualParamVo;
import com.ruoyi.drinkwater.service.ManualStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/drinkwater/manualStatistics")
public class ManualStatisticsController extends BaseController {

    @Autowired
    private ManualStatisticsService manualStatisticsService;

    @GetMapping("/getManualTendency")
    public AjaxResult getManualTendency(ManualParamVo vo){
       Map<String,Object> list=manualStatisticsService.getManualTendency(vo);
        return AjaxResult.success(list);
    }

    /**
     * 环境管理状况汇总-水源地
     * @Param [drinkSourceName 水源地名称, dataTypeid 1区划 2水源地类型 3水源地级别, drinkSourceType 不同类型的编码 区划编码 水源地类型（河流-1/湖库-2/地下水-3） 水源地级别（0城市、1县级以上、2千吨万人、3千人以上、4乡镇、5其他）
     *     , pageNum 页数, pageSize 条数, mgryear 年份]
     **/
    @GetMapping("/summaryEnvironmentalDrinkSource")
    public Map summaryEnvironmentalDrinkSource(String drinkSourceName,String dataTypeid,String drinkSourceType,Integer pageNum, Integer pageSize,String mgryear ,String region, String sydlevel ) {
        Map map = new HashMap();//存放传入参数


        map.put("dataTypeid", dataTypeid);
        map.put("drinkSourceName", drinkSourceName);
        map.put("mgryear", mgryear);
        map.put("region", region);
        List<String> drinksourceTypes = new ArrayList<>();
        if (drinkSourceType!=null&&!"".equals(drinkSourceType)) {
            String[] arr = drinkSourceType.split(",");
            drinksourceTypes = Arrays.asList(arr);
            map.put("drinksourceType",drinksourceTypes);
        }
        //水源地级别参数
        if(StringUtils.isNotEmpty(sydlevel)){
            String [] strs = sydlevel.split(",");
            List<String> leveList = Arrays.asList(strs);
            map.put("sydLevels",leveList);

        }
        //查询监测数据
        List<Map<Object, Object>> list = manualStatisticsService.summaryEnvironmentalDrinkSource(map);
        //没有办法调用工具和sql进行分页调用Java 对应方法进行分页查询
        List<Map> collect = list.stream().skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        //获取总条数
        int size = list.size();
        //返回数据结果集
        Map maplist = new HashMap();
        maplist.put("data", collect);
        maplist.put("code", 200);
        maplist.put("msg", "查询成功");
        maplist.put("total", size);
        return maplist;
    }

    @GetMapping("/getScoreDrinkSource")
    public Map getScoreDrinkSource(String mgryear , String sydlevel ,Integer pageNum, Integer pageSize) {
        Map map = new HashMap();//存放传入参数
        map.put("mgryear", mgryear);
        //水源地级别参数
        if(StringUtils.isNotEmpty(sydlevel)){
            String [] strs = sydlevel.split(",");
            List<String> leveList =Arrays.asList(strs);
            map.put("sydLevels",leveList);

        }
        List<Map<String, Object>> list = new ArrayList<>();
        //环境管理状况汇总
        List<Map<String, Object>> list1 = manualStatisticsService.SummaryEnvironmentalManagement(map);
        //取水量汇总
        List<Map<String, Object>> list2 = manualStatisticsService.getWaterDrinkSource(map);

        //根据环境管理状况汇总和取水量汇总，计算各项分数
        if (null != list1){
            for (Map<String, Object> map2 : list1) {
                Object countyCode = map2.get("countyCode");//城镇
                Object isDivide = map2.get("isDivide");//保护区完成率
                Object isSettingFlag = map2.get("isSettingFlag");//保护区标志设置完成率
                Object alreadyPartition = map2.get("alreadyPartition");//一级保护区隔离完成率
                Object dxWM = map2.get("dxWM");//监测完成率地下水
                Object dbWM = map2.get("dbWM");//监测完成率地表水
                Object pcr1 = map2.get("pcr1");//一级保护区整治率
                Object pcr2 = map2.get("pcr2");//二级保护区整治率
                Object pcqr = map2.get("pcqr");//准保护区整治率
                Object rmrs = map2.get("rmrs");//风险管理指标完成率
                Object onemes = map2.get("onemes");//应急管理指标完成率地表水
                Object inemes = map2.get("inemes");//应急管理指标完成率地下水
                Object msrs = map2.get("msrs");//管理制度完成率

                //TODO;逻辑待完善
                Map<String, Object> resultMap = new HashMap();

                resultMap.put("county",map2.get("county"));
                resultMap.put("countyCode",map2.get("CountyCode"));
                resultMap.put("province",map2.get("province"));

                Object wg = 0;
                Object sq = 0;
                Object ms = 0;
                Object swes = 0;
                Object jkScore = 0;
                Object yjScore = 0;
                if(list2 != null && list2.size() > 0){
                    //数据分组
                    List<Map<String, Object>> qsl = list2.stream()
                            .filter(item -> item.get("CountyCode").equals(countyCode)
                            )
                            .collect(Collectors.toList());

                    //根据不同权重，计算相应达标分值
                    for(Map<String, Object>  qs : qsl) {
                        Object qslbz = qs.get("qsthisYearWgr");//取水量保证状况
                        Object sydb = qs.get("sydbthisYearWqr");//水源达标状况
                        Object sldb = qs.get("slthisYearWsr");//水量达标状况
                        wg = Double.valueOf(String.valueOf(qslbz));
                        sq = Double.valueOf(String.valueOf(sydb))*0.3 + Double.valueOf(String.valueOf(sldb))*0.7;
                    }
                }
                // 创建一个DecimalFormat对象，指定格式为两位小数
                DecimalFormat dr = new DecimalFormat("0.00");

                //监测监控及应急能力 未提示地表水，地下水。故不做区分，取两者均值
                jkScore = (Double.valueOf(String.valueOf(dxWM)) + Double.valueOf(String.valueOf(dbWM)))/2;
                yjScore = (Double.valueOf(String.valueOf(onemes)) + Double.valueOf(String.valueOf(inemes)))/2;
                //管理状况
                ms = Double.valueOf(String.valueOf(isDivide))*0.1 + Double.valueOf(String.valueOf(isSettingFlag))*0.05 +
                        Double.valueOf(String.valueOf(alreadyPartition))*0.1 +  Double.valueOf(String.valueOf(pcr1))*0.1 +
                        Double.valueOf(String.valueOf(pcr2))*0.1 + Double.valueOf(String.valueOf(pcqr))*0.05 +
                        Double.valueOf(String.valueOf(rmrs))*0.15 + Double.valueOf(String.valueOf(yjScore))*0.15 +
                        Double.valueOf(String.valueOf(msrs))*0.1+ Double.valueOf(String.valueOf(jkScore))*0.1;
                //环境保护状况
                swes = Double.valueOf(String.valueOf(wg))*0.1 + Double.valueOf(String.valueOf(sq))*0.6 +
                        Double.valueOf(String.valueOf(ms))*0.3;

                resultMap.put("swes",dr.format(swes));
                if ( Double.valueOf(swes.toString())>=90){
                    resultMap.put("swesResult","优秀");
                } else if ( 80<=Double.valueOf(swes.toString()) && Double.valueOf(swes.toString()) <90){
                    resultMap.put("swesResult","良好");
                } else if ( 70<=Double.valueOf(swes.toString()) && Double.valueOf(swes.toString()) <80){
                    resultMap.put("swesResult","合格");
                } else if ( 60<=Double.valueOf(swes.toString()) && Double.valueOf(swes.toString()) <70){
                    resultMap.put("swesResult","基本不合格");
                } else if ( Double.valueOf(swes.toString()) <60 && Double.valueOf(swes.toString()) >0){
                    resultMap.put("swesResult","不合格");
                }else{
                    resultMap.put("swesResult","--");
                }

                resultMap.put("wg",dr.format(wg));
                resultMap.put("sq",dr.format(sq));
                resultMap.put("ms",dr.format(ms));

                resultMap.put("hfScore",isDivide);
                resultMap.put("bzScore",isSettingFlag);
                resultMap.put("glScore",alreadyPartition);
                resultMap.put("jkScore",jkScore);
                resultMap.put("pcr1",pcr1);
                resultMap.put("pcr2",pcr2);
                resultMap.put("pcqr",pcqr);
                resultMap.put("fxfkScore",rmrs);
                resultMap.put("yjScore",yjScore);
                resultMap.put("glcScore",msrs);

                list.add(resultMap);
            }
        }

        //没有办法调用工具和sql进行分页调用Java 对应方法进行分页查询
        List<Map> collect = list.stream().skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        //获取总条数
        int size = list.size();
        //返回数据结果集
        Map maplist = new HashMap();
        maplist.put("data", collect);
        maplist.put("code", 200);
        maplist.put("msg", "查询成功");
        maplist.put("total", size);
        return maplist;
    }

    @GetMapping("/isoverDrinkSourcelist")
    public Map isoverDrinkSourcelist(String drinkSourceName,String dataTypeid,String itemName,Integer pageNum, Integer pageSize,String dataType,String beginTime,String endTime,String drinksources,String countyCode,String drinkSourceType,String drinkSourceLevel,String isWhether) {
        Map map = new HashMap();//存放传入参数
        List<String> itemNames = new ArrayList<>();
        if (itemName != null && !"".equals(itemName)) {
            String[] arr = itemName.split(",");
            itemNames = Arrays.asList(arr);
            map.put("itemNames", itemNames);
        }
        map.put("dataTypeid", dataTypeid);
        if (isWhether != null && !"".equals(isWhether)) {
            map.put("isWhether", isWhether);

        } else {
            map.put("isWhether", "0");
        }
        if (dataType != null && !"".equals(dataType)) {
            map.put("dataType", dataType);
        } else {
            map.put("dataType", "0");
        }
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("drinkSourceName", drinkSourceName);
        List<String> countyCodes = new ArrayList<>();
        if (countyCode != null && !"".equals(countyCode)) {
            String[] arr = countyCode.split(",");
            countyCodes = Arrays.asList(arr);
            map.put("countyCode", countyCodes);
        }
        List<String> drinksourceTypes = new ArrayList<>();
        if (drinkSourceType != null && !"".equals(drinkSourceType)) {
            String[] arr = drinkSourceType.split(",");
            drinksourceTypes = Arrays.asList(arr);
            map.put("drinksourceType", drinksourceTypes);
        }
        List<String> drinksourcess = new ArrayList<>();
        if (drinksources != null && !"".equals(drinksources)) {
            String[] arr = drinksources.split(",");
            drinksourcess = Arrays.asList(arr);
            map.put("drinksources", drinksourcess);
        }
        List<String> drinkSourceLevels = new ArrayList<>();
        if (drinkSourceLevel != null && !"".equals(drinkSourceLevel)) {
            String[] arr = drinkSourceLevel.split(",");
            drinkSourceLevels = Arrays.asList(arr);
            map.put("drinkSourceLevel", drinkSourceLevels);
        }

        List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
        //查询监测数据
        List<Map<Object, Object>> list1 = manualStatisticsService.isoverDrinkSourcelist(map);
        if ("1".equals(map.get("isWhether"))) {
            Map<String, Object> stringObjectMap = DateUtils.OnTheSameMonthRatio(String.valueOf(beginTime), String.valueOf(endTime), "yyyy-MM");
            if (stringObjectMap != null && stringObjectMap.size() > 0) {
                beginTime = (String) stringObjectMap.get("tbksData");
                endTime = (String) stringObjectMap.get("tbjsData");
                map.put("beginTime", beginTime);
                map.put("endTime", endTime);
            }

            //获取同比数据
            List<Map<Object, Object>> list2 = manualStatisticsService.isoverDrinkSourcelist(map);
            if (list1.size() > list2.size()) {
                for (Map<Object, Object> map1 : list1) {
                    map1.put("type", "当期");
                    list.add(map1);
                    // 根据id字段分组
                    Map<Object, List<Map<Object, Object>>> groupedData = list2.stream()
                            .collect(Collectors.groupingBy(
                                    maps -> (Object) maps.get("drinksourceId"), // 这里假设id字段是Object类型，根据实际情况调整
                                    Collectors.toList()
                            ));

                    if (groupedData.keySet().contains(map1.get("drinksourceId"))) {
                        Map<Object, Object> map2 = groupedData.get(map1.get("drinksourceId")).get(0);
                        map2.put("type", "同比");
                        list.add(groupedData.get(map1.get("drinksourceId")).get(0));
                    } else {
                        //Map<Object, Object> map3 = map1;
                        Map<Object, Object> map3 = new HashMap(map1);
                        map3.put("type", "同比");
                        map3.put("dbqsl", null);
                        map3.put("evaluationResults", null);
                        map3.put("evaluationScore", null);
                        map3.put("isover", null);
                        map3.put("qsl", null);
                        map3.put("qualityLevelName", null);
                        map3.put("qualityLevel", null);
                        map3.put("dbMonths", null);
                        map3.put("waterVolume", null);
                        map3.put("cbOverStandard", null);
                        list.add(map3);
                    }

                }
            }else{
                for (Map<Object, Object> map1 : list2) {
                    map1.put("type", "同比");

                    // 根据id字段分组
                    Map<Object, List<Map<Object, Object>>> groupedData = list1.stream()
                            .collect(Collectors.groupingBy(
                                    maps -> (Object) maps.get("drinksourceId"), // 这里假设id字段是Object类型，根据实际情况调整
                                    Collectors.toList()
                            ));

                    if (groupedData.keySet().contains(map1.get("drinksourceId"))) {
                        Map<Object, Object> map2 = groupedData.get(map1.get("drinksourceId")).get(0);
                        map2.put("type", "当期");
                        list.add(groupedData.get(map1.get("drinksourceId")).get(0));
                    } else {
                        //Map<Object, Object> map3 = map1;
                        Map<Object, Object> map3 = new HashMap(map1);
                        map3.put("type", "当期");
                        map3.put("dbqsl", null);
                        map3.put("evaluationResults", null);
                        map3.put("evaluationScore", null);
                        map3.put("isover", null);
                        map3.put("qsl", null);
                        map3.put("qualityLevelName", null);
                        map3.put("qualityLevel", null);
                        map3.put("dbMonths", null);
                        map3.put("waterVolume", null);
                        map3.put("cbOverStandard", null);
                        list.add(map3);
                    }
                    list.add(map1);
                }
            }
        }  else {
            list = list1;
        }


        //没有办法调用工具和sql进行分页调用Java 对应方法进行分页查询
        List<Map> collect = list.stream().skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        //获取总条数
        int size = list.size();
        //返回数据结果集
        Map maplist = new HashMap();
        maplist.put("data", collect);
        maplist.put("code", 200);
        maplist.put("msg", "查询成功");
        maplist.put("total", size);
        return maplist;
    }

    @GetMapping("/drinkSourcewaterQuality")
    public Map drinkSourcewaterQuality(String drinkType,String drinkSourceName,String dataTypeid,String dataType,String beginTime,String endTime,String drinksources,String countyCode,String drinkSourceType,String drinkSourceLevel,String isWhether) {
        Map map = new HashMap();//存放传入参数
        map.put("dataTypeid", dataTypeid);
        map.put("drinkType", drinkType);
        map.put("drinkSourceName", drinkSourceName);
        if(isWhether!=null&&!"".equals(isWhether)){
            map.put("isWhether", isWhether);
        }else {
            map.put("isWhether", "0");
        }
        if(dataType!=null&&!"".equals(dataType)){
            map.put("dataType", dataType);
        }else {
            map.put("dataType", "0");
        }
        if(beginTime!=null&&!"".equals(beginTime)){
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
        }
        List<String> countyCodes = new ArrayList<>();
        if (countyCode!=null&&!"".equals(countyCode)) {
            String[] arr = countyCode.split(",");
            countyCodes = Arrays.asList(arr);
            map.put("countyCode",countyCodes);
        }
        List<String> drinksourceTypes = new ArrayList<>();
        if (drinkSourceType!=null&&!"".equals(drinkSourceType)) {
            String[] arr = drinkSourceType.split(",");
            drinksourceTypes = Arrays.asList(arr);
            map.put("drinksourceType",drinksourceTypes);
        }
        List<String> drinksourcess = new ArrayList<>();
        if (drinksources!=null&&!"".equals(drinksources)) {
            String[] arr = drinksources.split(",");
            drinksourcess = Arrays.asList(arr);
            map.put("drinksources",drinksourcess);
        }
        List<String> drinkSourceLevels = new ArrayList<>();
        if (drinkSourceLevel!=null&&!"".equals(drinkSourceLevel)) {
            String[] arr = drinkSourceLevel.split(",");
            drinkSourceLevels = Arrays.asList(arr);
            map.put("drinkSourceLevel",drinkSourceLevels);
        }
        //查询监测数据
        Map map1 = manualStatisticsService.drinkSourcewaterQuality(map);
        //返回数据结果集
        Map maplist = new HashMap();
        maplist.put("data", map1);
        maplist.put("code", 200);
        maplist.put("msg", "查询成功");
        return maplist;
    }

/**
 * 水源地趋势变化分析-断面与因子变化趋势
 *
 */
    @GetMapping("/drinkSourceTrend")
    public AjaxResult getDrinkSourceTrend(String segmentId, String dataType, String itemCode,  String beginTime, String endTime) {
        Map<String,Object> map = manualStatisticsService.getDrinkSourceTrend(segmentId,  dataType,  itemCode,   beginTime,  endTime);
        return AjaxResult.success(map);
    }

}
